<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :auto-upload="true"
      :file-list="imageList"
      :http-request="handleUpload"
      :before-upload="beforeAvatarUpload"
      :on-change="handleChange"
      :on-success="handleAvatarSuccess"
      :on-preview="handlePictureCardPreview"
      :before-remove="beforeRemove"
      :on-remove="handleRemove">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
/**
 * 使用的elementui的上传组件“照片墙”
 * https://element.eleme.cn/#/zh-CN/component/upload#zhao-pian-qiang
 *
 * minio的js库文档：
 * https://www.bookstack.cn/read/MinioCookbookZH/19.md
 */
import 'element-ui/lib/theme-chalk/index.css'
// eslint-disable-next-line no-unused-vars
import {Minio, Client} from 'minio' // 导入 minio 的js库
// eslint-disable-next-line no-unused-vars
// import nodejs from 'nodejs'
export default {
  name: 'MinioUpload',
  data () {
    return {
      imageUploadCount: 0, // 上传文件计数
      imageList: [], // 文件列表
      dialogImageUrl: '',
      dialogVisible: false,
      imageLimitCount: 5
    }
  },
  created () {
  },
  methods: {
    // 上传文件的函数
    // todo 官网的例子是基于nodejs的代码的，上传的文件类型只能是Buffer、readable.Stream、string其中的一种
    // todo 但是纯前端无法获得文件的Buffer或者readable.Stream对象,只能上传string类型的简单文本对象
    handleUpload (request) {
      console.log('上传文件 -> ', request)
      const file = request.file
      // 构建上传对象
      try {
        var minioClient = new Client({
          endPoint: '127.0.0.1',
          port: 9000,
          useSSL: false,
          accessKey: 'minioadmin',
          secretKey: 'minioadmin'
        })
        // console.log(minioClient)
        // const obj = await file.arrayBuffer()
        file.arrayBuffer().then((data) => {
          console.log(data)
          var metaData = {
            'Content-Type': 'text/plain'
          }
          minioClient.putObject('test', 'a2.txt', 'this is string', metaData, function (err, etag) {
            if (err) {
              return console.log(err, etag)
            }
            console.log('Success', err, etag)
          })
        }, (err) => {
          console.log(err)
        })
      } catch (e) {
        console.log('异常：', e)
      }
    },
    handleChange (file, fileList) {
      console.log('正在上传 -> ', file, fileList)
      // this.imageList.push(file)
    },
    /**
     * 上传文件之前的回调函数
     * @param file
     * @returns {boolean}
     */
    beforeAvatarUpload (file) {
      console.log('上传之前 -> ', file)
      if (this.imageUploadCount >= this.imageLimitCount) {
        this.$message.error(`很抱歉目前只允许上传${this.imageLimitCount}张图片!`)
        return false
      }
      let isJPG = false
      const fileTypeList = ['image/x-icon', 'image/png', 'image/jpeg', 'image/bmp', 'image/gif']
      const fileType = file.type
      for (let index in fileTypeList) {
        if (fileType === fileTypeList[index]) {
          isJPG = true
          break
        }
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 png、jpg、jpeg、bmp、gif、x-icon 其中一种格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    /**
     * 上传成功的回调函数
     * @param res
     * @param file
     */
    handleAvatarSuccess (res, file) {
      console.log('上传成功 -> ', res, file)
      this.dialogImageUrl = URL.createObjectURL(file.raw)
      this.imageUploadCount += 1
    },
    // 删除文件之前的回调
    beforeRemove (file, fileList) {
      console.log('删除之前 -> ', file, fileList)
      return this.$msgbox.confirm(`确定移除 ${file.name}？`)
    },
    /**
     * 删除文件
     * @param file
     * @param fileList
     */
    handleRemove (file, fileList) {
      console.log('删除文件 -> ', file, fileList)
      this.imageUploadCount -= 1
    },
    /**
     * 图片预览的回调函数
     * @param file
     */
    handlePictureCardPreview (file) {
      console.log('预览文件 -> ', file)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>

<style scoped>

</style>
